<template>
  <a-card>
    <div class="a-search">
      <div :style="{ height }" class="a-search-form">
        <a-form ref="formElement" v-model="form" :list="formList" :inline="true">
          <template #[item]="{ props }" v-for="(item, index) in Object.keys($slots)" :key="index">
            <slot :name="item" :props="props"></slot>
          </template>
        </a-form>
      </div>
      <div class="a-search-button">
        <el-button type="primary" @click="handleSearch">
          <span class="icon-search"></span>
          <span>查询</span>
        </el-button>
        <el-button @click="handleReset">
          <span class="icon-cz"></span>
          <span>重置</span>
        </el-button>
        <el-button @click="handleMore" v-if="max < list.length">
          <span class="icon-more"></span>
          <span>更多</span>
        </el-button>
      </div>
    </div>
  </a-card>
</template>

<script setup lang="ts" generic="T extends FormItem">
import { computed, nextTick, ref } from 'vue'
import sass from '../assets/scss/variable.module.scss'

defineOptions({
  name: 'a-search'
})

interface Props {
  list: T[]
  change?: (reset?: boolean) => void
}

const props = withDefaults(defineProps<Props>(), {
  change: () => {}
})

const form = defineModel<FormModel>({ required: true })

const formElement = ref<AFormInstance | null>(null)

const more = ref(false)
const defaultHeight = ref(sass.formItemHeight)
const height = ref(defaultHeight.value)
const max = computed(() => Number(sass.formItemMax))
const formList = ref<T[]>([...setFormList()]) as Ref<T[]>

function setFormList() {
  const list = [...props.list]
  props.list.forEach((item, index) => {
    item.formItemProps = {
      style: {
        width: sass.formItemWidth,
        display: more.value ? 'block' : index >= max.value ? 'none' : 'block'
      }
    }
  })
  return list
}

function handleSearch() {
  props.change(true)
}

function handleMore() {
  more.value = !more.value
  formList.value = setFormList()
  nextTick(() => {
    if (more.value) {
      height.value = formElement.value!.$el.offsetHeight + 'px'
    } else {
      height.value = defaultHeight.value
    }
  })
}

function handleReset() {
  const element = formElement.value!.element
  element.resetFields()
  props.change(true)
}
</script>

<style lang="scss">
.a-search {
  width: 100%;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  &-form {
    width: calc(calc(#{$form-item-width}) * $form-item-max);
    overflow: hidden;
    transition: all 0.3s;
  }
  &-button {
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    gap: 10px;
    .el-button {
      margin-left: 0px !important;
    }
  }
}
</style>
